﻿<template>
  <div class="profile-page">

    <div class="profile-container">
      <!-- 左侧导航菜单 -->
      <div class="sidebar">
        <div class="sidebar-header">
          <div class="user-avatar-section">
            <div class="user-avatar">
              <img v-if="userInfo.avatar" :src="userInfo.avatar" :alt="userInfo.username" class="avatar-img">
              <div v-else class="avatar-placeholder" :style="{ backgroundColor: getAvatarBgColor(userInfo.username), color: 'white' }">
                {{ getAvatarText(userInfo.username) }}
              </div>
            </div>
            <div class="user-name">{{ userInfo.username || '未知用户' }}</div>
          </div>
        </div>
        
        <ul class="sidebar-menu">
          <li class="menu-item" :class="{ active: activeTab === 'personal-info' }" @click="setActiveTab('personal-info')">
            <i class="icon">👤</i>
            <span>个人信息</span>
          </li>
          <li class="menu-item" :class="{ active: activeTab === 'homework' }" @click="setActiveTab('homework')">
            <i class="icon">📚</i>
            <span>我的作业</span>
          </li>
          <li class="menu-item" :class="{ active: activeTab === 'password' }" @click="setActiveTab('password')">
            <i class="icon">🔒</i>
            <span>修改密码</span>
          </li>
        </ul>
      </div>
      
      <!-- 右侧内容区域 -->
      <div class="main-content">
        <!-- 个人信息 -->
        <div v-if="activeTab === 'personal-info'" class="content-section">
          <div class="section-header">
            <h2>个人信息</h2>
            <button @click="refreshUserInfo" class="refresh-btn" :disabled="isRefreshing">
              <span v-if="isRefreshing">🔄 刷新中...</span>
              <span v-else>🔄 刷新信息</span>
            </button>
          </div>
          
          <div class="personal-info-form">
            <!-- 头像上传区域 -->
            <div class="avatar-section">
              <label class="form-label">我的头像</label>
              <div class="avatar-upload">
                <div class="avatar-preview">
                  <img v-if="personalInfo.avatar" :src="personalInfo.avatar" alt="用户头像" />
                  <div v-else class="avatar-placeholder">
                    {{ getAvatarText(personalInfo.nickname || personalInfo.username || '未') }}
                  </div>
                </div>
              </div>
            </div>



            <!-- 昵称 -->
            <div class="form-group">
              <label class="form-label">*昵称</label>
              <input 
                type="text" 
                v-model="personalInfo.nickname"
                class="form-input"
                placeholder="请输入昵称"
              />
            </div>

            <!-- 手机号码 -->
            <div class="form-group">
              <label class="form-label">手机号码</label>
              <input 
                type="text" 
                v-model="personalInfo.mobile"
                class="form-input"
                placeholder="请输入手机号码"
              />
            </div>

            <!-- 身份证号码 -->
            <div class="form-group">
              <label class="form-label">身份证号码</label>
              <input 
                type="text" 
                v-model="personalInfo.idCard"
                class="form-input"
                placeholder="填写真实身份证号码"
              />
            </div>

            <!-- 住址 -->
            <div class="form-group">
              <label class="form-label">住址</label>
              <input 
                type="text" 
                v-model="personalInfo.address"
                class="form-input"
                placeholder="请输入详细住址"
              />
            </div>

            <!-- 工作单位/学校 -->
            <div class="form-group">
              <label class="form-label">*工作单位/学校</label>
              <input 
                type="text" 
                v-model="personalInfo.workplace"
                class="form-input"
                placeholder="请输入工作单位/学校"
              />
            </div>

            <!-- 身份 -->
            <div class="form-group">
              <label class="form-label">身份</label>
              <input 
                type="text" 
                v-model="personalInfo.identity"
                class="form-input"
                placeholder="请输入身份"
              />
            </div>

            <!-- 性别 -->
            <div class="form-group">
              <label class="form-label">性别</label>
              <select v-model="personalInfo.gender" class="form-input">
                <option value="">请选择性别</option>
                <option value="男">男</option>
                <option value="女">女</option>
              </select>
            </div>

            <!-- 电子邮箱 -->
            <div class="form-group">
              <label class="form-label">电子邮箱</label>
              <input 
                type="email" 
                v-model="personalInfo.email"
                class="form-input"
                placeholder="请输入电子邮箱"
              />
            </div>

            <!-- 简介 -->
            <div class="form-group">
              <label class="form-label">简介</label>
              <textarea 
                v-model="personalInfo.introduction"
                class="form-textarea"
                placeholder="填写个人简介"
                rows="4"
              ></textarea>
            </div>

            <!-- 操作按钮 -->
            <div class="form-actions">
              <button @click="savePersonalInfo" class="save-btn" :disabled="isSavingPersonalInfo">
                <span v-if="isSavingPersonalInfo">保存中...</span>
                <span v-else>提交</span>
              </button>
              <button @click="resetPersonalInfoForm" class="reset-btn">重置</button>
            </div>
          </div>
        </div>
        
        <!-- 我的作业 -->
        <div v-if="activeTab === 'homework'" class="content-section">
          <div class="section-header">
            <h2>我的班级作业</h2>
          </div>
          
          <!-- 班级列表 -->
          <div v-if="teamList.length > 0" class="teams-section">
            <h3 class="section-subtitle">我的班级 (共 {{ teamList.length }} 个)</h3>
            <div class="teams-grid">
              <div 
                v-for="team in teamList" 
                :key="team.id" 
                class="team-card"
                :class="{ 'selected': selectedTeam && selectedTeam.id === team.id }"
                @click="selectTeam(team)"
              >
                <div class="team-card-header">
                  <span class="team-icon">🏫</span>
                  <h4 class="team-name">{{ team.teamName }}</h4>
                  <span v-if="selectedTeam && selectedTeam.id === team.id" class="selected-badge">✓ 已选择</span>
                </div>
                <div v-if="team.teamIntroduction" class="team-intro">
                  {{ team.teamIntroduction }}
                </div>
                <div class="team-card-footer">
                  <button 
                    @click.stop="queryTeamHomework(team)" 
                    class="query-team-btn"
                    :disabled="isLoadingHomework"
                  >
                    <span v-if="isLoadingHomework && selectedTeam && selectedTeam.id === team.id">🔄 查询中...</span>
                    <span v-else>🔍 查询作业</span>
                  </button>
                </div>
              </div>
            </div>
          </div>
          
          <!-- 当前选中班级的作业标题 -->
          <div v-if="selectedTeam && homeworkList.length > 0" class="selected-team-info">
            <h3>📚 {{ selectedTeam.teamName }} - 作业列表</h3>
          </div>
          
          <!-- 作业列表 -->
          <div v-if="homeworkList.length > 0" class="homework-list-section">
            <h3 class="list-title">📚 作业列表 (共 {{ totalHomework }} 个)</h3>
            <div class="homework-table">
              <table>
                <thead>
                  <tr>
                    <th>作业ID</th>
                    <th>作业标题</th>
                    <th>发布时间</th>
                    <th>截止时间</th>
                    <th>状态</th>
                    <th>操作</th>
                  </tr>
                </thead>
                <tbody>
                  <tr v-for="hw in homeworkList" :key="hw.id">
                    <td>{{ hw.id }}</td>
                    <td>{{ hw.title || hw.description || hw.homeworkName || '无标题' }}</td>
                    <td>{{ formatDate(hw.startTime || hw.createTime) }}</td>
                    <td>{{ formatDate(hw.deadline || hw.endTime) }}</td>
                    <td>
                      <span class="status-badge" :class="getStatusClass(hw)">
                        {{ getStatusText(hw) }}
                      </span>
                    </td>
                    <td>
                      <button @click="viewHomework(hw)" class="action-btn view-btn">
                        📝 查看作业
                      </button>
                    </td>
                  </tr>
                </tbody>
              </table>
            </div>
            
            <!-- 分页控件 -->
            <div v-if="homeworkList.length > 0" class="homework-pagination">
              <button 
                @click="prevHomeworkPage" 
                :disabled="homeworkPage === 1"
                class="page-btn"
              >
                上一页
              </button>
              <span class="page-info">
                第 {{ homeworkPage }} / {{ totalPages }} 页 (共 {{ totalHomework }} 条)
              </span>
              <div class="page-jump">
                <input 
                  v-model.number="jumpToPage" 
                  type="number" 
                  min="1" 
                  :max="totalPages"
                  placeholder="页码"
                  class="page-input"
                  @keyup.enter="jumpToHomeworkPage"
                />
                <button @click="jumpToHomeworkPage" class="jump-btn">跳转</button>
              </div>
              <button 
                @click="nextHomeworkPage" 
                :disabled="homeworkPage >= totalPages"
                class="page-btn"
              >
                下一页
              </button>
            </div>
          </div>
          
          <!-- 空状态提示 -->
          <div v-else-if="teamList.length === 0 && !isLoadingHomework" class="empty-state">
            <div class="empty-icon">🏫</div>
            <p class="empty-text">暂无班级信息</p>
          </div>
          
          <div v-else-if="selectedTeam && homeworkList.length === 0 && !isLoadingHomework" class="empty-state">
            <div class="empty-icon">📭</div>
            <p class="empty-text">该班级暂无作业</p>
          </div>
        </div>
        
        <!-- 修改密码 -->
        <div v-if="activeTab === 'password'" class="content-section">
          <div class="section-header">
            <h2>修改密码</h2>
          </div>
          
          <div class="password-form">
            <div class="form-group">
              <label>输入旧密码：</label>
              <div class="password-input-wrapper">
                <input 
                  :type="showOldPassword ? 'text' : 'password'" 
                  v-model="passwordForm.oldPassword" 
                  placeholder="请输入当前密码" 
                  class="form-input password-input"
                >
                <button 
                  type="button" 
                  @click="showOldPassword = !showOldPassword" 
                  class="toggle-password-btn"
                  :title="showOldPassword ? '隐藏密码' : '显示密码'"
                >
                  {{ showOldPassword ? '👁️' : '👁️‍🗨️' }}
                </button>
              </div>
              <div class="error-message" v-if="passwordErrors.oldPassword">{{ passwordErrors.oldPassword }}</div>
            </div>
            
            <div class="form-group">
              <label>输入新密码：</label>
              <div class="password-input-wrapper">
                <input 
                  :type="showNewPassword ? 'text' : 'password'" 
                  v-model="passwordForm.newPassword" 
                  placeholder="请输入新密码" 
                  class="form-input password-input"
                >
                <button 
                  type="button" 
                  @click="showNewPassword = !showNewPassword" 
                  class="toggle-password-btn"
                  :title="showNewPassword ? '隐藏密码' : '显示密码'"
                >
                  {{ showNewPassword ? '👁️' : '👁️‍🗨️' }}
                </button>
              </div>
              <div class="error-message" v-if="passwordErrors.newPassword">{{ passwordErrors.newPassword }}</div>
            </div>
            
            <div class="form-group">
              <label>确认新密码：</label>
              <div class="password-input-wrapper">
                <input 
                  :type="showConfirmPassword ? 'text' : 'password'" 
                  v-model="passwordForm.confirmPassword" 
                  placeholder="请再次输入新密码" 
                  class="form-input password-input"
                >
                <button 
                  type="button" 
                  @click="showConfirmPassword = !showConfirmPassword" 
                  class="toggle-password-btn"
                  :title="showConfirmPassword ? '隐藏密码' : '显示密码'"
                >
                  {{ showConfirmPassword ? '👁️' : '👁️‍🗨️' }}
                </button>
              </div>
              <div class="error-message" v-if="passwordErrors.confirmPassword">{{ passwordErrors.confirmPassword }}</div>
            </div>
            
            <div class="form-actions">
              <button @click="changePassword" :disabled="isChangingPassword" class="submit-btn">
                <span v-if="isChangingPassword">修改中...</span>
                <span v-else>更改密码</span>
              </button>
              <button @click="resetPasswordForm" class="reset-btn">重置</button>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 查询作业对话框 -->
    <div v-if="showQueryDialog" class="dialog-overlay" @click="closeQueryDialog">
      <div class="dialog-container" @click.stop>
        <div class="dialog-header">
          <h3>🔍 查询作业</h3>
          <button class="close-btn" @click="closeQueryDialog">×</button>
        </div>
        
        <div class="dialog-body">
          <div class="form-field">
            <label class="required">团队ID</label>
            <input 
              v-model="queryForm.teamId" 
              type="text" 
              placeholder="请输入团队ID（支持大整数）"
              class="dialog-input"
            />
            <span class="field-hint">💡 输入团队ID后，将查询该团队下的所有作业</span>
          </div>
        </div>
        
        <div class="dialog-footer">
          <button @click="closeQueryDialog" class="cancel-btn">取消</button>
          <button @click="confirmQuery" class="confirm-btn">确认查询</button>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { userApi, testLargeNumberHandling } from '@/api'
import { buildImageURL } from '@/config/api-config'
import logger from '../utils/logger.js'

export default {
  name: 'UserProfile',
  data() {
    return {
      activeTab: 'personal-info', // 默认显示个人信息标签页
      userInfo: {},
      
      // 个人信息数据
      personalInfo: {
        avatar: '',
        nickname: '',
        mobile: '',
        idCard: '',
        address: '',
        workplace: '',
        identity: '',
        gender: '',
        email: '',
        introduction: ''
      },
      originalPersonalInfo: {}, // 保存原始数据用于重置
      isSavingPersonalInfo: false,
      isRefreshing: false, // 刷新用户信息状态
      
      // 作业列表
      homeworkList: [],
      homeworkPage: 1,
      totalHomework: 0,
      homeworkPageSize: 10,
      homeworkTotalPages: 1,  // 总页数
      jumpToPage: null,  // 跳转页码
      isLoadingHomework: false,
      
      // 班级信息（支持多个班级）
      teamList: [], // 所有班级列表
      selectedTeam: null, // 当前选中的班级
      
      // 查询作业对话框
      showQueryDialog: false,
      queryForm: {
        teamId: ''
      },
      
      // 修改密码
      passwordForm: {
        oldPassword: '',
        newPassword: '',
        confirmPassword: ''
      },
      passwordErrors: {},
      isChangingPassword: false,
      // 密码显示状态
      showOldPassword: false,
      showNewPassword: false,
      showConfirmPassword: false
    }
  },
  
  mounted() {
    logger.log('🔄 [Profile] 个人中心页面已挂载，开始初始化...')
    
    // 检查登录状态
    const token = localStorage.getItem('token')
    logger.log('🔑 [Profile] JWT令牌状态:', token ? '存在' : '不存在')
    if (token) {
      logger.log('🔑 [Profile] JWT令牌预览:', token.substring(0, 50) + '...')
      logger.log('🔑 [Profile] JWT令牌长度:', token.length)
    }
    
    // 检查路由query参数，如果有tab参数则切换到对应标签页
    if (this.$route.query.tab) {
      const targetTab = this.$route.query.tab
      logger.log('🔍 [Profile] 检测到tab参数:', targetTab)
      this.activeTab = targetTab
      
      // 如果是作业标签，需要加载作业数据
      if (targetTab === 'homework') {
        logger.log('📚 [Profile] 自动切换到我的作业标签')
        this.loadHomework()
      }
    }
    
    this.loadUserInfo()
    this.loadPersonalInfo()
    this.loadUserInfoFromAPI()  // 从API加载用户详细信息
    // 注意：不在页面加载时调用作业列表，只在点击"我的作业"标签时才加载
  },
  
  computed: {
    // 计算总页数
    totalPages() {
      return this.homeworkTotalPages || Math.ceil(this.totalHomework / this.homeworkPageSize) || 1
    }
  },
  
  methods: {
    // 获取用户角色 - 从JWT令牌中解析
    getUserRole() {
      try {
        const token = localStorage.getItem('token')
        if (token) {
          // JWT令牌由三部分组成，用.分隔：header.payload.signature
          const parts = token.split('.')
          if (parts.length === 3) {
            // 解码payload部分（base64url编码）
            const payload = parts[1]
            // 添加必要的padding
            const paddedPayload = payload + '='.repeat((4 - payload.length % 4) % 4)
            // base64url解码
            const decodedPayload = atob(paddedPayload.replace(/-/g, '+').replace(/_/g, '/'))
            const payloadObj = JSON.parse(decodedPayload)
            
            // 从claims中获取role
            if (payloadObj.claims && payloadObj.claims.role) {
              return payloadObj.claims.role
            }
          }
        }
        
        // 如果JWT解析失败，从localStorage获取
        const userInfo = JSON.parse(localStorage.getItem('userInfo') || '{}')
        // role可能是数字或字符串，统一转换为数字
        if (userInfo.role === 'student' || userInfo.role === 3 || userInfo.role === '3') {
          return 3
        }
        if (userInfo.role === 'teacher' || userInfo.role === 2 || userInfo.role === '2') {
          return 2
        }
        return userInfo.role || 0
        
      } catch (error) {
        console.error('获取用户角色失败:', error)
        return 0
      }
    },
    
    loadUserInfo() {
      const userInfoStr = localStorage.getItem('userInfo')
      if (userInfoStr) {
        this.userInfo = JSON.parse(userInfoStr)
      }
    },
    
    // 从API加载用户详细信息
    async loadUserInfoFromAPI() {
      try {
        logger.log('🔍 [Profile] 开始从API加载用户详细信息...')
        
        // 首先检查JWT令牌
        const token = localStorage.getItem('token')
        if (!token) {
          logger.error('❌ [Profile] 没有JWT令牌，无法调用API')
          this.$message?.error?.('请先登录') || alert('请先登录')
          this.$router.push('/login')
          return
        }
        
        logger.log('🔑 [Profile] JWT令牌验证通过')
        
        // 测试大数字处理
        logger.log('🧪 [Profile] 运行大数字精度测试...')
        testLargeNumberHandling()
        
        // 手动测试JWT解析
        logger.log('🧪 [Profile] 手动测试JWT解析...')
        const testToken = localStorage.getItem('token')
        if (testToken) {
          logger.log('🔍 [Profile] 测试令牌存在，长度:', testToken.length)
          logger.log('🔍 [Profile] 测试令牌格式:', testToken.includes('.') ? 'JWT格式' : '非JWT格式')
          
          // 尝试手动解析
          try {
            const parts = testToken.split('.')
            logger.log('🔍 [Profile] 令牌分段:', parts.length)
            if (parts.length === 3) {
              const payload = JSON.parse(atob(parts[1].replace(/-/g, '+').replace(/_/g, '/')))
              logger.log('🔍 [Profile] 手动解析payload:', payload)
            }
          } catch (e) {
            logger.error('❌ [Profile] 手动解析失败:', e)
          }
        } else {
          logger.log('❌ [Profile] 测试令牌不存在')
        }
        
        // 调用新的getUserHomeInfo接口
        logger.log('📞 [Profile] 准备调用userApi.getUserHomeInfo()...')
        
        const response = await userApi.getUserHomeInfo()
        
        logger.log('📞 [Profile] API调用完成，响应:', response)
        
        if (response && response.data) {
          logger.log('✅ [Profile] API用户信息加载成功:', response.data)
          
          // 更新用户基本信息显示
          if (response.data.userName || response.data.username || response.data.nickname || response.data.name) {
            this.userInfo.username = response.data.userName || response.data.username || response.data.nickname || response.data.name
          }
          
          if (response.data.avatar || response.data.avatarUrl) {
            this.userInfo.avatar = response.data.avatar || response.data.avatarUrl
          }
          
          // 更新个人信息表单数据
          // 根据接口返回的实际字段结构进行映射
          this.personalInfo = {
            ...this.personalInfo,
            // 基本信息 - 根据接口返回的字段名
            nickname: response.data.userName || response.data.nickname || response.data.username || response.data.name || this.personalInfo.nickname,
            mobile: response.data.phone || this.personalInfo.mobile, // 接口返回phone字段
            email: response.data.email || this.personalInfo.email,
            avatar: buildImageURL(response.data.profilePicture || response.data.avatar || this.personalInfo.avatar),
            
            // 详细信息 - 根据接口返回的字段名
            idCard: response.data.idCard || this.personalInfo.idCard,
            address: response.data.address || this.personalInfo.address, // 接口返回address字段
            workplace: response.data.unit || response.data.workplace || this.personalInfo.workplace, // 接口返回unit字段
            identity: response.data.identity || response.data.grade || this.personalInfo.identity, // 将grade字段映射到identity
            gender: response.data.gender || this.personalInfo.gender,
            introduction: response.data.userIntroduction || response.data.introduction || this.personalInfo.introduction // 接口返回userIntroduction字段
          }
          
          logger.log('📋 [Profile] 字段映射详情:');
          logger.log('  - userName:', response.data.userName || '无');
          logger.log('  - nickname:', response.data.nickname || '无');
          logger.log('  - email:', response.data.email || '无');
          logger.log('  - profilePicture:', response.data.profilePicture || '无');
          logger.log('  - address:', response.data.address || '无');
          logger.log('  - unit:', response.data.unit || '无');
          logger.log('  - grade:', response.data.grade || '无');
          logger.log('  - userIntroduction:', response.data.userIntroduction || '无');
          
          // 更新原始数据（用于重置功能）
          this.originalPersonalInfo = { ...this.personalInfo }
          
          // 同步更新localStorage中的用户信息
          const localUserInfo = {
            ...JSON.parse(localStorage.getItem('userInfo') || '{}'),
            username: this.personalInfo.nickname,
            nickname: this.personalInfo.nickname,
            email: this.personalInfo.email,
            avatar: this.personalInfo.avatar,
            // 保存API返回的原始用户名
            realName: response.data.userName || this.personalInfo.nickname
          }
          localStorage.setItem('userInfo', JSON.stringify(localUserInfo))
          
                    logger.log('✅ [Profile] 用户信息已更新到页面')
          logger.log('🎉 [Profile] ===== 接口调用完全成功 =====')
          
          // 导入统一API配置显示实际接口地址
          const { default: API_CONFIG } = await import('@/api/apiConfig.js');
          logger.log(`🎉 [Profile] 接口地址: ${API_CONFIG.getFullURL('/goc/user/userHomeInfo')}`)
        logger.log('🎉 [Profile] 用户ID: 1953810929896525824')
        logger.log('🎉 [Profile] 响应状态: 成功')
        logger.log('🎉 [Profile] 用户姓名:', response.data.userName)
        logger.log('🎉 [Profile] =============================')
          
        } else {
          logger.warn('⚠️ [Profile] API返回的用户信息为空')
        }
        
      } catch (error) {
        logger.error('❌ [Profile] 从API加载用户信息失败:', error)
        logger.error('❌ [Profile] 错误详情:')
        logger.error('  - 错误消息:', error.message)
        logger.error('  - 错误类型:', error.constructor.name)
        logger.error('  - 错误堆栈:', error.stack)
        
        if (error.response) {
          logger.error('  - HTTP状态码:', error.response.status)
          logger.error('  - 响应数据:', error.response.data)
          logger.error('  - 响应头:', error.response.headers)
        } else if (error.request) {
          logger.error('  - 请求对象:', error.request)
        }
        
        // 根据错误类型提供用户友好的提示
        let errorMessage = '加载用户信息失败'
        if (error.message && error.message.includes('无法获取用户ID')) {
          errorMessage = '登录状态异常，请重新登录'
        } else if (error.response?.status === 401) {
          errorMessage = '登录已过期，请重新登录'
        } else if (error.response?.status === 404) {
          errorMessage = '用户信息不存在'
        } else if (error.response?.status >= 500) {
          errorMessage = '服务器错误，请稍后重试'
        }
        
        // 显示错误信息（如果有消息组件的话）
        if (this.$message?.warning) {
          this.$message.warning(errorMessage)
        } else {
          logger.warn('⚠️ [Profile] ' + errorMessage)
        }
      }
    },
    
    // 手动刷新用户信息
    async refreshUserInfo() {
      if (this.isRefreshing) return
      
      try {
        this.isRefreshing = true
        logger.log('🔄 [Profile] 手动刷新用户信息...')
        
        await this.loadUserInfoFromAPI()
        
        logger.log('✅ [Profile] 用户信息已刷新')
        
      } catch (error) {
        logger.error('❌ [Profile] 刷新用户信息失败:', error)
        
        if (this.$message?.error) {
          this.$message.error('刷新失败，请稍后重试')
        }
      } finally {
        this.isRefreshing = false
      }
    },
    
    setActiveTab(tab) {
      this.activeTab = tab
      
      // 只在切换到"我的作业"标签时才加载作业数据
      if (tab === 'homework') {
        logger.log('📚 [Profile] 切换到我的作业标签，开始加载作业数据...')
        this.loadHomework()
      }
    },
    
    // 头像相关方法
    getAvatarBgColor(username) {
      if (!username) return '#666'
      const colors = ['#FF6B6B', '#4ECDC4', '#45B7D1', '#96CEB4', '#FFEAA7', '#DDA0DD', '#98D8C8', '#F7DC6F']
      const index = username.charCodeAt(0) % colors.length
      return colors[index]
    },
    
    getAvatarText(username) {
      if (!username) return '?'
      return username.charAt(0).toUpperCase()
    },
    
    // 个人信息相关方法
    async loadPersonalInfo() {
      try {
        logger.log('🔍 加载个人信息...')
        
        // 从localStorage获取基本信息
        const localUserInfo = localStorage.getItem('userInfo')
        if (localUserInfo) {
          const localData = JSON.parse(localUserInfo)
          this.personalInfo.nickname = localData.username || this.personalInfo.nickname
          this.personalInfo.email = localData.email || this.personalInfo.email
        }
        
        // 注意：不调用 getUserProfile 接口（后端已移除该接口）
        // 个人信息从 loadUserInfoFromAPI() 中的 getUserHomeInfo 接口获取
        
        // 保存原始数据
        this.originalPersonalInfo = { ...this.personalInfo }
        
        logger.log('✅ 个人信息加载完成:', this.personalInfo)
        
      } catch (error) {
        logger.error('❌ 加载个人信息失败:', error)
      }
    },
    
    // 保存个人信息
    async savePersonalInfo() {
      if (this.isSavingPersonalInfo) return
      
      try {
        this.isSavingPersonalInfo = true
        logger.log('💾 开始保存个人信息...')
        
        // 基本验证
        if (!this.personalInfo.nickname) {
          this.$message?.error?.('请输入昵称') || alert('请输入昵称')
          return
        }
        
        if (!this.personalInfo.workplace) {
          this.$message?.error?.('请输入工作单位/学校') || alert('请输入工作单位/学校')
          return
        }
        
        // 构建提交数据
        const submitData = {
          nickname: this.personalInfo.nickname,
          mobile: this.personalInfo.mobile,
          idCard: this.personalInfo.idCard,
          address: this.personalInfo.address,
          workplace: this.personalInfo.workplace,
          identity: this.personalInfo.identity,
          gender: this.personalInfo.gender,
          email: this.personalInfo.email,
          introduction: this.personalInfo.introduction
        }
        
        logger.log('📤 提交数据:', submitData)
        
        // 调用新的统一更新接口
        const results = []
        
        logger.log('👤 调用用户完整信息更新接口...')
        try {
          const response = await userApi.updateUserCompleteInfo(submitData)
          logger.log('✅ 用户信息更新成功:', response)
          results.push({ type: '用户信息', success: true, response: response })
        } catch (error) {
          logger.error('❌ 用户信息更新失败:', error)
          results.push({ type: '用户信息', success: false, error: error })
        }
        
        // 如果有手机号或邮箱信息，还需要调用更新手机号/邮箱接口（如果该接口独立处理）
        if (this.personalInfo.mobile || this.personalInfo.email) {
          logger.log('📞 调用手机号/邮箱更新接口...')
          try {
            const phoneEmailResponse = await userApi.updatePhoneOrEmail(
              this.personalInfo.mobile, 
              this.personalInfo.email
            )
            logger.log('✅ 手机号/邮箱更新成功:', phoneEmailResponse)
            results.push({ type: '手机号/邮箱', success: true, response: phoneEmailResponse })
          } catch (error) {
            logger.error('❌ 手机号/邮箱更新失败:', error)
            results.push({ type: '手机号/邮箱', success: false, error: error })
          }
        }
        
        logger.log('💾 所有更新操作结果:', results)
        
        // 分析所有API调用的结果
        const successCount = results.filter(r => r.success).length
        const totalCount = results.length
        const hasAnySuccess = successCount > 0
        const allSuccess = successCount === totalCount
        
        if (allSuccess) {
          logger.log('✅ [Profile] 个人信息保存成功')
        } else if (hasAnySuccess) {
          // 部分成功
          const successTypes = results.filter(r => r.success).map(r => r.type).join('、')
          const failTypes = results.filter(r => !r.success).map(r => r.type).join('、')
          const message = `部分信息保存成功（${successTypes}），${failTypes}保存失败`
          this.$message?.warning?.(message) || alert(message)
        } else {
          // 全部失败
          this.$message?.error?.('个人信息保存失败！') || alert('个人信息保存失败！')
          return
        }
        
        if (hasAnySuccess) {
          
          // 更新localStorage中的用户信息
          const localUserInfo = localStorage.getItem('userInfo')
          if (localUserInfo) {
            const localData = JSON.parse(localUserInfo)
            localData.username = this.personalInfo.nickname
            localData.email = this.personalInfo.email
            localStorage.setItem('userInfo', JSON.stringify(localData))
          }
          
          // 更新原始数据和用户信息
          this.originalPersonalInfo = { ...this.personalInfo }
          this.userInfo.username = this.personalInfo.nickname
        }
        
      } catch (error) {
        logger.error('❌ 保存个人信息失败:', error)
        
        let errorMsg = '保存失败，请稍后重试'
        if (error.response?.status === 401) {
          errorMsg = '登录已过期，请重新登录'
        } else if (error.response?.data?.message) {
          errorMsg = error.response.data.message
        } else if (error.response?.data?.msg) {
          errorMsg = error.response.data.msg
        }
        
        this.$message?.error?.(errorMsg) || alert(errorMsg)
        
      } finally {
        this.isSavingPersonalInfo = false
      }
    },
    
    // 重置个人信息表单
    resetPersonalInfoForm() {
      if (confirm('确定要重置所有修改吗？')) {
        this.personalInfo = { ...this.originalPersonalInfo }
        this.$message?.info?.('表单已重置') || logger.log('表单已重置')
      }
    },
    
    // 作业相关方法
    async loadHomework() {
      this.isLoadingHomework = true
      try {
        logger.log('📚 [Profile] 加载我的班级信息...')
        
        // 获取用户ID
        const { getCurrentUserId } = await import('@/utils/userIdUtils')
        const userId = getCurrentUserId()
        
        if (!userId) {
          logger.error('❌ [Profile] 无法获取用户ID')
          this.$message?.error?.('无法获取用户信息，请重新登录') || alert('无法获取用户信息，请重新登录')
          return
        }
        
        logger.log('👤 [Profile] 当前用户ID:', userId)
        
        // 调用团队接口获取班级列表
        const { teamApi } = await import('@/api/team')
        const response = await teamApi.findById(userId)
        
        logger.log('✅ [Profile] 班级信息加载成功:', response)
        
        // 处理响应数据
        if (response && response.code === 0) {
          if (response.data) {
            // 后端返回的可能是数组（多个班级）或单个对象
            if (Array.isArray(response.data)) {
              // 多个班级
              this.teamList = response.data.map(team => ({
                id: team.id,
                teamName: team.teamName || '',
                teamIntroduction: team.teamIntroduction || ''
              }))
              logger.log('🏫 [Profile] 加载了 ' + this.teamList.length + ' 个班级:', this.teamList)
              
              // 默认选择第一个班级
              if (this.teamList.length > 0) {
                this.selectedTeam = this.teamList[0]
                logger.log('✅ [Profile] 默认选择第一个班级:', this.selectedTeam.teamName)
              }
            } else {
              // 单个班级对象
              this.teamList = [{
                id: response.data.id,
                teamName: response.data.teamName || '',
                teamIntroduction: response.data.teamIntroduction || ''
              }]
              this.selectedTeam = this.teamList[0]
              logger.log('🏫 [Profile] 班级信息（单个）:', this.teamList[0])
            }
            
            // 清空作业列表，等待用户点击查询
            this.homeworkList = []
            this.totalHomework = 0
            logger.log('ℹ️ [Profile] 班级信息加载完成，作业列表为空（需点击查询作业按钮）')
          } else {
            // data 为 null 的情况
            logger.log('ℹ️ [Profile] 暂无班级数据（data 为 null）')
            this.teamList = []
            this.selectedTeam = null
            this.homeworkList = []
            this.totalHomework = 0
          }
        } else {
          // 接口调用失败
          logger.warn('⚠️ [Profile] 接口返回异常:', response)
          this.teamList = []
          this.selectedTeam = null
          this.homeworkList = []
          this.totalHomework = 0
        }
      } catch (error) {
        logger.error('❌ [Profile] 加载班级信息失败:', error)
        this.$message?.error?.('加载班级信息失败') || alert('加载班级信息失败')
      } finally {
        this.isLoadingHomework = false
      }
    },
    
    refreshHomework() {
      this.homeworkPage = 1
      this.loadHomework()
    },
    
    // 选择班级
    selectTeam(team) {
      this.selectedTeam = team
      logger.log('✅ [Profile] 选择班级:', team.teamName)
      
      // 清空之前的作业列表和分页信息
      this.homeworkList = []
      this.totalHomework = 0
      this.homeworkPage = 1
      this.homeworkTotalPages = 1
      this.jumpToPage = null
    },
    
    // 查询指定班级的作业
    async queryTeamHomework(team, resetPage = true) {
      // 检查是否有班级ID
      if (!team || !team.id) {
        const msg = '班级信息异常，无法查询作业'
        logger.warn('⚠️ [Profile]', msg)
        this.$message?.warning?.(msg) || alert(msg)
        return
      }
      
      // 选择该班级
      this.selectedTeam = team
      
      // 如果是新查询，重置页码为1
      if (resetPage) {
        this.homeworkPage = 1
        logger.log('🔄 [Profile] 重置页码为1')
      }
      
      try {
        logger.log('🔍 [Profile] 查询班级作业')
        logger.log('🔍 [Profile] 班级名称:', team.teamName)
        logger.log('🔍 [Profile] 班级ID:', team.id)
        logger.log('📄 [Profile] 当前页码:', this.homeworkPage)
        
        this.isLoadingHomework = true
        
        // 动态导入homework API
        const homeworkApi = await import('@/api/homework')
        
        // 调用查询团队作业的API（传递分页参数）
        const response = await homeworkApi.getHomeworkByTeamId(
          String(team.id),
          this.homeworkPage,
          this.homeworkPageSize
        )
        
        logger.log('✅ [Profile] 团队作业查询成功:', response)
        
        // 处理响应数据
        if (response && response.code === 0) {
          const data = response.data
          
          logger.log('📦 [Profile] 解析的数据:', data)
          
          // 获取用户角色
          const userRole = this.getUserRole()
          logger.log('👤 [Profile] 当前用户角色:', userRole)
          
          // 如果返回的是数组
          if (Array.isArray(data)) {
            let homeworkRecords = data
            
            // 🔥 学生也可以查看已截止的作业（但在作业详情页不能提交）
            logger.log('📋 [Profile] 显示所有作业（包括已截止）')
            logger.log('📋 [Profile] 作业数量:', homeworkRecords.length)
            
            this.homeworkList = homeworkRecords
            this.totalHomework = homeworkRecords.length
            logger.log('📋 [Profile] 查询到作业数量:', this.homeworkList.length)
            
            // 静默查询，不显示成功提示
            logger.log(`✅ [Profile] 查询成功，共 ${homeworkRecords.length} 个作业`)
          }
          // 如果返回的是分页数据结构
          else if (data && (data.records || data.list)) {
            let homeworkRecords = data.records || data.list || []
            
            // 🔥 学生也可以查看已截止的作业（但在作业详情页不能提交）
            logger.log('📋 [Profile] 显示所有作业（包括已截止）')
            logger.log('📋 [Profile] 作业数量:', homeworkRecords.length)
            
            this.homeworkList = homeworkRecords
            this.totalHomework = data.total || homeworkRecords.length  // 从分页数据中获取总数
            this.homeworkTotalPages = data.pages || Math.ceil(this.totalHomework / this.homeworkPageSize)  // 获取总页数
            
            logger.log('📋 [Profile] 查询到作业数量:', this.homeworkList.length)
            logger.log('📋 [Profile] 总记录数:', this.totalHomework)
            logger.log('📋 [Profile] 总页数:', this.homeworkTotalPages)
            logger.log('📋 [Profile] 当前页:', this.homeworkPage)
            
            // 静默查询，不显示成功提示
            logger.log(`✅ [Profile] 查询成功，第${this.homeworkPage}页，共 ${this.totalHomework} 个作业`)
          }
          // 其他情况
          else {
            this.homeworkList = []
            this.totalHomework = 0
            logger.log('⚠️ [Profile] 查询结果为空')
            
            const msg = `${team.teamName} 暂无作业`
            this.$message?.info?.(msg) || alert(msg)
          }
        } else {
          // 业务错误
          const errorMsg = response?.message || '查询失败'
          logger.error('❌ [Profile] 业务错误:', errorMsg)
          this.$message?.error?.(errorMsg) || alert(errorMsg)
        }
        
      } catch (error) {
        logger.error('❌ [Profile] 查询作业失败:', error)
        
        let errorMsg = '查询失败，请稍后重试'
        if (error.response?.status === 404) {
          errorMsg = '未找到该班级的作业'
        } else if (error.response?.data?.message) {
          errorMsg = error.response.data.message
        } else if (error.message) {
          errorMsg = error.message
        }
        
        this.$message?.error?.(errorMsg) || alert(errorMsg)
      } finally {
        this.isLoadingHomework = false
      }
    },
    
    // 打开查询对话框（已废弃，改用直接点击班级卡片查询）
    async openQueryDialog() {
      // 使用选中的班级查询
      if (this.selectedTeam) {
        await this.queryTeamHomework(this.selectedTeam)
      }
    },
    
    // 关闭查询对话框
    closeQueryDialog() {
      this.showQueryDialog = false
      this.queryForm.teamId = ''
    },
    
    // 确认查询作业
    async confirmQuery() {
      // 验证团队ID
      if (!this.queryForm.teamId) {
        alert('请输入团队ID！')
        return
      }
      
      // 验证是否为纯数字
      if (!/^\d+$/.test(this.queryForm.teamId)) {
        alert('团队ID必须是纯数字！')
        return
      }
      
      try {
        logger.log('🔍 [Profile] 开始查询团队作业')
        logger.log('🔍 [Profile] 团队ID:', this.queryForm.teamId)
        logger.log('🔍 [Profile] 团队ID类型:', typeof this.queryForm.teamId)
        
        this.isLoadingHomework = true
        
        // 动态导入homework API
        const homeworkApi = await import('@/api/homework')
        
        // 调用查询团队作业的API
        const response = await homeworkApi.getHomeworkByTeamId(this.queryForm.teamId)
        
        logger.log('✅ [Profile] 团队作业查询成功:', response)
        logger.log('🔍 [Profile] 响应数据结构:', {
          hasResponse: !!response,
          hasCode: response?.code !== undefined,
          code: response?.code,
          hasData: !!response?.data,
          dataType: response?.data ? typeof response.data : 'undefined'
        })
        
        // 处理响应数据
        // 注意：axios响应拦截器已经返回了response.data，所以这里的response就是后端返回的数据
        if (response && response.code === 0) {
          const data = response.data
          
          logger.log('📦 [Profile] 解析的数据:', data)
          logger.log('📦 [Profile] 数据类型:', Array.isArray(data) ? '数组' : typeof data)
          
          // 获取用户角色
          const userRole = this.getUserRole()
          logger.log('👤 [Profile] 当前用户角色:', userRole)
          
          // 如果返回的是数组
          if (Array.isArray(data)) {
            let homeworkRecords = data
            
            // 🔥 学生也可以查看已截止的作业（但在作业详情页不能提交）
            logger.log('📋 [Profile] 显示所有作业（包括已截止）')
            logger.log('📋 [Profile] 作业数量:', homeworkRecords.length)
            
            this.homeworkList = homeworkRecords
            this.totalHomework = homeworkRecords.length
            logger.log('📋 [Profile] 查询到作业数量（数组格式）:', this.homeworkList.length)
            
            // 静默查询，不显示成功提示
            logger.log(`✅ [Profile] 查询成功，共找到 ${homeworkRecords.length} 个作业`)
          }
          // 如果返回的是分页数据结构
          else if (data && (data.records || data.list)) {
            let homeworkRecords = data.records || data.list || []
            
            // 获取用户角色
            const userRole = this.getUserRole()
            logger.log('👤 [Profile] 当前用户角色:', userRole)
            
            // 🔥 学生也可以查看已截止的作业（但在作业详情页不能提交）
            logger.log('📋 [Profile] 显示所有作业（包括已截止）')
            logger.log('📋 [Profile] 作业数量:', homeworkRecords.length)
            
            this.homeworkList = homeworkRecords
            this.totalHomework = homeworkRecords.length
            logger.log('📋 [Profile] 查询到作业数量（分页格式）:', this.homeworkList.length)
            logger.log('📋 [Profile] 总记录数:', this.totalHomework)
            logger.log('📋 [Profile] 作业列表详情:', this.homeworkList)
            
            // 静默查询，不显示成功提示
            logger.log(`✅ [Profile] 查询成功，共找到 ${this.homeworkList.length} 个作业`)
          }
          // 其他情况
          else {
            this.homeworkList = []
            this.totalHomework = 0
            logger.log('⚠️ [Profile] 查询结果为空或格式不符')
            logger.log('⚠️ [Profile] 实际数据:', data)
            
            if (this.$message?.info) {
              this.$message.info('该团队暂无作业')
            } else {
              alert('该团队暂无作业')
            }
          }
        } else {
          // 业务错误
          const errorMsg = response?.message || '查询失败'
          logger.error('❌ [Profile] 业务错误:', errorMsg)
          logger.error('❌ [Profile] 响应code:', response?.code)
          
          if (this.$message?.error) {
            this.$message.error(errorMsg)
          } else {
            alert(errorMsg)
          }
        }
        
        // 重置分页
        this.homeworkPage = 1
        
        // 关闭对话框
        this.closeQueryDialog()
        
      } catch (error) {
        logger.error('❌ [Profile] 查询作业失败:', error)
        
        let errorMsg = '查询失败，请稍后重试'
        if (error.response?.status === 404) {
          errorMsg = '未找到该团队的作业'
        } else if (error.response?.data?.message) {
          errorMsg = error.response.data.message
        } else if (error.message) {
          errorMsg = error.message
        }
        
        if (this.$message?.error) {
          this.$message.error(errorMsg)
        } else {
          alert(errorMsg)
        }
      } finally {
        this.isLoadingHomework = false
      }
    },
    
    prevHomeworkPage() {
      if (this.homeworkPage > 1) {
        this.homeworkPage--
        logger.log('📄 [Profile] 上一页，当前页:', this.homeworkPage)
        // 重新查询当前班级作业（不重置页码）
        if (this.selectedTeam) {
          this.queryTeamHomework(this.selectedTeam, false)
        }
      }
    },
    
    nextHomeworkPage() {
      if (this.homeworkPage < this.totalPages) {
        this.homeworkPage++
        logger.log('📄 [Profile] 下一页，当前页:', this.homeworkPage)
        // 重新查询当前班级作业（不重置页码）
        if (this.selectedTeam) {
          this.queryTeamHomework(this.selectedTeam, false)
        }
      }
    },
    
    // 跳转到指定页
    jumpToHomeworkPage() {
      if (!this.jumpToPage || this.jumpToPage < 1 || this.jumpToPage > this.totalPages) {
        const msg = `请输入有效的页码（1-${this.totalPages}）`
        this.$message?.warning?.(msg) || alert(msg)
        return
      }
      
      this.homeworkPage = this.jumpToPage
      logger.log('📄 [Profile] 跳转到第', this.homeworkPage, '页')
      
      // 重新查询当前班级作业（不重置页码）
      if (this.selectedTeam) {
        this.queryTeamHomework(this.selectedTeam, false)
      }
      
      // 清空输入框
      this.jumpToPage = null
    },
    
    // 查看作业详情并开始做答
    async viewHomework(homework) {
      logger.log('📝 [Profile] 查看作业:', homework)
      logger.log('📝 [Profile] 作业ID:', homework.id)
      
      try {
        // 调用作业详情接口获取完整信息
        const homeworkApi = await import('@/api/homework')
        const response = await homeworkApi.getHomeworkDetail(homework.id)
        
        logger.log('✅ [Profile] 作业详情获取成功:', response)
        
        if (response && response.code === 0 && response.data) {
          // 将作业详情存储到localStorage，供详情页使用
          localStorage.setItem('currentHomework', JSON.stringify(response.data))
          
          // 跳转到作业详情页面
          this.$router.push({
            path: '/homework-detail',
            query: { 
              id: homework.id
            }
          })
        } else {
          const errorMsg = response?.message || '获取作业详情失败'
          if (this.$message?.error) {
            this.$message.error(errorMsg)
          } else {
            alert(errorMsg)
          }
        }
      } catch (error) {
        logger.error('❌ [Profile] 获取作业详情失败:', error)
        
        let errorMsg = '获取作业详情失败'
        if (error.response?.data?.message) {
          errorMsg = error.response.data.message
        } else if (error.message) {
          errorMsg = error.message
        }
        
        if (this.$message?.error) {
          this.$message.error(errorMsg)
        } else {
          alert(errorMsg)
        }
      }
    },
    
    // 格式化日期
    formatDate(dateStr) {
      if (!dateStr) return '-'
      try {
        const date = new Date(dateStr)
        if (isNaN(date.getTime())) return dateStr
        return date.toLocaleString('zh-CN', {
          year: 'numeric',
          month: '2-digit',
          day: '2-digit',
          hour: '2-digit',
          minute: '2-digit'
        })
      } catch (error) {
        return dateStr
      }
    },
    
    // 获取作业状态类名
    getStatusClass(homework) {
      // 如果作业已提交
      if (homework.isSubmitted) {
        return 'status-completed'
      }
      
      // 🔥 判断作业是否已截止（支持 deadline 和 endTime 字段）
      const endTimeStr = homework.deadline || homework.endTime
      if (!endTimeStr) {
        return 'status-pending'
      }
      
      const now = new Date().getTime()
      const endTime = new Date(endTimeStr).getTime()
      
      // 检查是否已截止
      if (!isNaN(endTime) && now > endTime) {
        return 'status-expired'
      } else {
        return 'status-pending'
      }
    },
    
    // 获取作业状态文本
    getStatusText(homework) {
      // 如果作业已提交
      if (homework.isSubmitted) {
        return '已完成'
      }
      
      // 🔥 判断作业是否已截止（支持 deadline 和 endTime 字段）
      const endTimeStr = homework.deadline || homework.endTime
      if (!endTimeStr) {
        return '进行中'
      }
      
      const now = new Date().getTime()
      const endTime = new Date(endTimeStr).getTime()
      
      // 检查是否已截止
      if (!isNaN(endTime) && now > endTime) {
        return '已截止'
      } else {
        return '进行中'
      }
    },
    
    // 修改密码相关方法
    validatePasswordForm() {
      this.passwordErrors = {}
      
      if (!this.passwordForm.oldPassword) {
        this.passwordErrors.oldPassword = '请输入当前密码'
      }
      
      if (!this.passwordForm.newPassword) {
        this.passwordErrors.newPassword = '请输入新密码'
      } else if (this.passwordForm.newPassword.length < 6) {
        this.passwordErrors.newPassword = '新密码长度不能少于6位'
      } else if (this.passwordForm.oldPassword === this.passwordForm.newPassword) {
        this.passwordErrors.newPassword = '新密码不能与旧密码相同'
      }
      
      if (!this.passwordForm.confirmPassword) {
        this.passwordErrors.confirmPassword = '请确认新密码'
      } else if (this.passwordForm.newPassword !== this.passwordForm.confirmPassword) {
        this.passwordErrors.confirmPassword = '两次输入的密码不一致'
      }
      
      return Object.keys(this.passwordErrors).length === 0
    },
    
    async changePassword() {
      if (!this.validatePasswordForm()) {
        return
      }
      
      this.isChangingPassword = true
      
      try {
        logger.log('🔑 开始修改密码...')
        
        // 调用更新密码接口（后端会自动验证旧密码）
        const response = await userApi.updatePassword(
          this.passwordForm.oldPassword,
          this.passwordForm.newPassword
        )
        
        logger.log('🔑 密码修改响应:', response)
        
        // 检查密码修改结果
        if (response && (response.code === 0 || response.code === '0')) {
          logger.log('✅ [Profile] 密码修改成功')
          this.resetPasswordForm()
          
          // 密码修改成功后，建议用户重新登录
          setTimeout(() => {
            if (confirm('密码已修改成功，为了安全起见，建议您重新登录。是否立即重新登录？')) {
              localStorage.removeItem('token')
              localStorage.removeItem('userInfo')
              this.$router.push('/login')
            }
          }, 1000)
          
        } else {
          const errorMsg = response?.message || response?.msg || '密码修改失败，请检查当前密码是否正确'
          this.$message?.error?.(errorMsg) || alert('密码修改失败：' + errorMsg)
        }
        
      } catch (error) {
        logger.error('修改密码失败:', error)
        let errorMsg = '密码修改失败，请稍后重试'
        
        // 根据错误类型提供更具体的错误信息
        if (error.response?.status === 401) {
          errorMsg = '当前密码错误，请重新输入'
        } else if (error.response?.status === 400) {
          errorMsg = '密码格式不正确，请检查输入'
        } else if (error.response?.status === 500) {
          errorMsg = '服务器错误，请稍后重试'
        } else if (error.response?.data?.message) {
          errorMsg = error.response.data.message
        } else if (error.response?.data?.msg) {
          errorMsg = error.response.data.msg
        } else if (error.message) {
          errorMsg = error.message
        }
        
        this.$message?.error?.(errorMsg) || alert(errorMsg)
      } finally {
        this.isChangingPassword = false
      }
    },
    
    resetPasswordForm() {
      this.passwordForm = {
        oldPassword: '',
        newPassword: '',
        confirmPassword: ''
      }
      this.passwordErrors = {}
      // 重置密码显示状态
      this.showOldPassword = false
      this.showNewPassword = false
      this.showConfirmPassword = false
    }
  }
}
</script>

<style scoped>
.profile-page {
  min-height: 100vh;
  background-color: #f5f5f5;
  padding: 20px;
}

.profile-container {
  max-width: 1400px;
  margin: 0 auto;
  display: flex;
  gap: 20px;
}

/* 左侧导航 */
.sidebar {
  width: 250px;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0,0,0,0.1);
  padding: 20px 0;
  height: fit-content;
}

.sidebar-header {
  padding: 0 20px 20px;
  border-bottom: 1px solid #eee;
}

.user-avatar-section {
  text-align: center;
}

.user-avatar {
  width: 80px;
  height: 80px;
  margin: 0 auto 10px;
  border-radius: 50%;
  overflow: hidden;
}

.avatar-img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.avatar-placeholder {
  width: 100%;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 32px;
  font-weight: bold;
}

.user-name {
  font-size: 18px;
  font-weight: 600;
  color: #333;
}

.sidebar-menu {
  list-style: none;
  padding: 0;
  margin: 20px 0 0 0;
}

.menu-item {
  padding: 12px 20px;
  cursor: pointer;
  display: flex;
  align-items: center;
  gap: 10px;
  color: #666;
  transition: all 0.3s ease;
}

.menu-item:hover {
  background-color: #f8f9fa;
  color: #333;
}

.menu-item.active {
  background-color: #4CAF50;
  color: white;
}

.menu-item .icon {
  font-size: 16px;
}

/* 右侧内容区 */
.main-content {
  flex: 1;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0,0,0,0.1);
  padding: 20px;
}

.section-header {
  margin-bottom: 20px;
  padding-bottom: 15px;
  border-bottom: 2px solid #4CAF50;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.section-header h2 {
  margin: 0;
  color: #333;
  font-size: 24px;
}

.refresh-btn {
  padding: 8px 16px;
  background: #2196F3;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
  transition: background-color 0.3s ease;
}

.refresh-btn:hover:not(:disabled) {
  background: #1976D2;
}

.refresh-btn:disabled {
  background: #ccc;
  cursor: not-allowed;
}

/* 个人信息表单样式 */
.personal-info-form {
  max-width: 600px;
}

.avatar-section {
  margin-bottom: 25px;
}

.avatar-upload {
  margin-top: 8px;
}

.avatar-preview {
  width: 120px;
  height: 120px;
  border-radius: 8px;
  overflow: hidden;
  border: 2px dashed #ddd;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #fafafa;
}

.avatar-preview img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.avatar-preview .avatar-placeholder {
  width: 100%;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 32px;
  font-weight: bold;
  color: #999;
  background-color: #f0f0f0;
}

.form-group {
  margin-bottom: 20px;
}

.form-label {
  display: block;
  margin-bottom: 8px;
  font-weight: 600;
  color: #333;
  font-size: 14px;
}

.form-input, .form-textarea {
  width: 100%;
  padding: 12px 16px;
  border: 1px solid #ddd;
  border-radius: 4px;
  font-size: 14px;
  box-sizing: border-box;
  transition: border-color 0.3s ease;
}

.form-input:focus, .form-textarea:focus {
  outline: none;
  border-color: #4CAF50;
  box-shadow: 0 0 0 2px rgba(76, 175, 80, 0.2);
}

.form-input[readonly] {
  background-color: #f5f5f5;
  color: #666;
}

.form-textarea {
  resize: vertical;
  min-height: 80px;
  font-family: inherit;
}



.search-filters {
  display: flex;
  gap: 10px;
  flex-wrap: wrap;
  align-items: center;
}

.filter-select, .filter-input {
  padding: 8px 12px;
  border: 1px solid #ddd;
  border-radius: 4px;
  font-size: 14px;
}

.search-btn {
  padding: 8px 16px;
  background: #4CAF50;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
}

.search-btn:hover {
  background: #45a049;
}

/* 表格样式 */
.submissions-table, .contests-table {
  overflow-x: auto;
}

table {
  width: 100%;
  border-collapse: collapse;
  margin-bottom: 20px;
}

th, td {
  padding: 12px;
  text-align: left;
  border-bottom: 1px solid #eee;
}

th {
  background: #4CAF50;
  color: white;
  font-weight: 600;
}

tr:hover {
  background-color: #f8f9fa;
}

.no-data {
  text-align: center;
  color: #999;
  font-style: italic;
}

.view-code-btn {
  padding: 4px 8px;
  background: #2196F3;
  color: white;
  border: none;
  border-radius: 3px;
  cursor: pointer;
  font-size: 12px;
}

.view-code-btn:hover {
  background: #1976D2;
}

/* 分页样式 */
.pagination {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 15px;
  margin-top: 20px;
}

.pagination-info {
  color: #666;
  font-size: 14px;
}

.page-btn {
  padding: 8px 16px;
  background: #4CAF50;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}

.page-btn:disabled {
  background: #ccc;
  cursor: not-allowed;
}

.current-page {
  padding: 8px 12px;
  background: #FF9800;
  color: white;
  border-radius: 4px;
  font-weight: 600;
}

/* 修改密码表单 */
.password-form {
  max-width: 500px;
  margin-top: 20px;
}

/* 密码输入框包装器 */
.password-input-wrapper {
  position: relative;
  display: flex;
  align-items: center;
}

.password-input-wrapper .password-input {
  flex: 1;
  padding-right: 50px;
}

.toggle-password-btn {
  position: absolute;
  right: 12px;
  background: none;
  border: none;
  cursor: pointer;
  font-size: 20px;
  padding: 4px 8px;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: all 0.2s ease;
  border-radius: 4px;
}

.toggle-password-btn:hover {
  background-color: #f0f0f0;
}

.toggle-password-btn:active {
  transform: scale(0.95);
}

/* 错误提示样式 */
.error-message {
  color: #f44336;
  font-size: 12px;
  margin-top: 6px;
  display: block;
}

/* 操作按钮 */
.form-actions {
  display: flex;
  gap: 15px;
  margin-top: 40px;
  padding-top: 20px;
  border-top: 1px solid #eee;
}

.save-btn {
  padding: 12px 30px;
  background: #4CAF50;
  color: white;
  border: none;
  border-radius: 6px;
  cursor: pointer;
  font-size: 16px;
  font-weight: 600;
  transition: background-color 0.3s ease;
}

.save-btn:hover:not(:disabled) {
  background: #45a049;
}

.save-btn:disabled {
  background: #ccc;
  cursor: not-allowed;
}

.reset-btn {
  padding: 12px 30px;
  background: #FF9800;
  color: white;
  border: none;
  border-radius: 6px;
  cursor: pointer;
  font-size: 16px;
  font-weight: 600;
  transition: background-color 0.3s ease;
}

.reset-btn:hover {
  background: #F57C00;
}

.submit-btn {
  padding: 12px 24px;
  background: #4CAF50;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 16px;
}

.submit-btn:hover:not(:disabled) {
  background: #45a049;
}

.submit-btn:disabled {
  background: #ccc;
  cursor: not-allowed;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .profile-container {
    flex-direction: column;
  }
  
  .sidebar {
    width: 100%;
  }
  
  .search-filters {
    flex-direction: column;
    align-items: stretch;
  }
  
  .filter-select, .filter-input {
    width: 100%;
  }
  
  .form-actions {
    flex-direction: column;
  }
  
  .save-btn, .reset-btn {
    width: 100%;
  }
  
  /* 班级卡片响应式 */
  .teams-grid {
    grid-template-columns: 1fr;
  }
  
  .team-card {
    padding: 16px;
  }
  
  .team-name {
    font-size: 16px;
  }
}

/* 作业列表样式 */
.homework-table {
  margin-top: 20px;
}

.homework-table table {
  width: 100%;
  border-collapse: collapse;
  background: white;
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.homework-table th {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  padding: 15px;
  text-align: left;
  font-weight: 600;
}

.homework-table td {
  padding: 15px;
  border-bottom: 1px solid #f0f0f0;
}

.homework-table tr:hover {
  background: #f8f9fa;
}

/* 作业分页样式 */
.homework-pagination {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 15px;
  margin-top: 25px;
  padding: 20px;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

.homework-pagination .page-btn {
  padding: 10px 20px;
  background: linear-gradient(135deg, #667eea, #764ba2);
  color: white;
  border: none;
  border-radius: 6px;
  font-size: 14px;
  font-weight: 600;
  cursor: pointer;
  transition: all 0.3s ease;
  box-shadow: 0 2px 8px rgba(102, 126, 234, 0.3);
}

.homework-pagination .page-btn:hover:not(:disabled) {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(102, 126, 234, 0.5);
}

.homework-pagination .page-btn:disabled {
  background: #ccc;
  cursor: not-allowed;
  transform: none;
  box-shadow: none;
}

.homework-pagination .page-info {
  font-size: 14px;
  color: #666;
  font-weight: 500;
}

.homework-pagination .page-jump {
  display: flex;
  align-items: center;
  gap: 8px;
}

.homework-pagination .page-input {
  width: 80px;
  padding: 8px 12px;
  border: 2px solid #e1e8ed;
  border-radius: 6px;
  font-size: 14px;
  text-align: center;
  transition: all 0.3s ease;
}

.homework-pagination .page-input:focus {
  outline: none;
  border-color: #667eea;
  box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1);
}

.homework-pagination .jump-btn {
  padding: 8px 16px;
  background: linear-gradient(135deg, #4CAF50, #45a049);
  color: white;
  border: none;
  border-radius: 6px;
  font-size: 14px;
  font-weight: 600;
  cursor: pointer;
  transition: all 0.3s ease;
  box-shadow: 0 2px 8px rgba(76, 175, 80, 0.3);
}

.homework-pagination .jump-btn:hover {
  background: linear-gradient(135deg, #388e3c, #2e7d32);
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(76, 175, 80, 0.4);
}

.status-badge {
  padding: 6px 12px;
  border-radius: 20px;
  font-size: 14px;
  font-weight: 500;
  display: inline-block;
}

.status-pending {
  background: #e3f2fd;
  color: #1976d2;
}

.status-completed {
  background: #e8f5e9;
  color: #388e3c;
}

.status-expired {
  background: #ffebee;
  color: #d32f2f;
}

.action-btn {
  padding: 8px 16px;
  border: none;
  border-radius: 6px;
  cursor: pointer;
  font-size: 14px;
  font-weight: 500;
  transition: all 0.3s ease;
}

.view-btn {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
}

.view-btn:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(102, 126, 234, 0.4);
}

.no-data {
  text-align: center;
  padding: 40px;
  color: #999;
  font-size: 16px;
}

/* 头部操作按钮组 */
.header-actions {
  display: flex;
  gap: 12px;
  align-items: center;
}

.query-btn {
  padding: 8px 16px;
  background: #4CAF50;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
  transition: background-color 0.3s ease;
}

.query-btn:hover {
  background: #45a049;
}

/* 查询对话框样式 */
.dialog-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
  animation: fadeIn 0.3s ease;
}

@keyframes fadeIn {
  from {
    opacity: 0;
  }
  to {
    opacity: 1;
  }
}

.dialog-container {
  background: white;
  border-radius: 16px;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.2);
  width: 90%;
  max-width: 500px;
  animation: slideUp 0.3s ease;
}

@keyframes slideUp {
  from {
    transform: translateY(50px);
    opacity: 0;
  }
  to {
    transform: translateY(0);
    opacity: 1;
  }
}

.dialog-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px 24px;
  border-bottom: 2px solid #f0f0f0;
}

.dialog-header h3 {
  margin: 0;
  font-size: 20px;
  color: #2c3e50;
  font-weight: 600;
}

.close-btn {
  background: none;
  border: none;
  font-size: 28px;
  color: #999;
  cursor: pointer;
  width: 32px;
  height: 32px;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 50%;
  transition: all 0.2s;
  line-height: 1;
}

.close-btn:hover {
  background: #f5f5f5;
  color: #666;
}

.dialog-body {
  padding: 24px;
}

.form-field {
  margin-bottom: 20px;
}

.form-field:last-child {
  margin-bottom: 0;
}

.form-field label {
  display: block;
  margin-bottom: 8px;
  font-size: 14px;
  color: #333;
  font-weight: 500;
}

.form-field label.required::after {
  content: ' *';
  color: #f44336;
  font-weight: bold;
}

.dialog-input {
  width: 100%;
  padding: 12px 16px;
  border: 1px solid #ddd;
  border-radius: 8px;
  font-size: 14px;
  transition: all 0.2s;
  box-sizing: border-box;
}

.dialog-input:focus {
  outline: none;
  border-color: #4CAF50;
  box-shadow: 0 0 0 3px rgba(76, 175, 80, 0.1);
}

.dialog-input::placeholder {
  color: #999;
}

.field-hint {
  display: block;
  margin-top: 6px;
  font-size: 12px;
  color: #666;
  line-height: 1.4;
}

.dialog-footer {
  padding: 16px 24px;
  border-top: 2px solid #f0f0f0;
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}

.cancel-btn,
.confirm-btn {
  padding: 10px 24px;
  border: none;
  border-radius: 8px;
  font-size: 14px;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.2s;
}

.cancel-btn {
  background: #f5f5f5;
  color: #666;
}

.cancel-btn:hover {
  background: #e0e0e0;
}

.confirm-btn {
  background: #4CAF50;
  color: white;
}

.confirm-btn:hover {
  background: #45a049;
  box-shadow: 0 4px 12px rgba(76, 175, 80, 0.3);
}

/* 对话框响应式设计 */
@media (max-width: 768px) {
  .dialog-container {
    width: 95%;
    margin: 0 10px;
  }

  .dialog-header,
  .dialog-body,
  .dialog-footer {
    padding: 16px;
  }

  .dialog-footer {
    flex-direction: column;
  }

  .cancel-btn,
  .confirm-btn {
    width: 100%;
  }
  
  .header-actions {
    flex-direction: column;
    width: 100%;
  }
  
  .query-btn,
  .refresh-btn {
    width: 100%;
  }
}

/* 班级列表样式 */
.teams-section {
  margin-bottom: 30px;
}

.section-subtitle {
  font-size: 18px;
  color: #333;
  margin-bottom: 16px;
  font-weight: 600;
}

.teams-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
  gap: 20px;
  margin-bottom: 24px;
}

.team-card {
  background: white;
  border: 2px solid #e0e0e0;
  border-radius: 12px;
  padding: 20px;
  cursor: pointer;
  transition: all 0.3s ease;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
}

.team-card:hover {
  border-color: #667eea;
  transform: translateY(-4px);
  box-shadow: 0 8px 24px rgba(102, 126, 234, 0.2);
}

.team-card.selected {
  border-color: #667eea;
  background: linear-gradient(135deg, rgba(102, 126, 234, 0.05) 0%, rgba(118, 75, 162, 0.05) 100%);
  box-shadow: 0 4px 16px rgba(102, 126, 234, 0.3);
}

.team-card-header {
  display: flex;
  align-items: center;
  gap: 10px;
  margin-bottom: 12px;
  position: relative;
}

.team-icon {
  font-size: 24px;
  line-height: 1;
}

.team-name {
  flex: 1;
  margin: 0;
  font-size: 18px;
  font-weight: 600;
  color: #333;
}

.selected-badge {
  position: absolute;
  top: -8px;
  right: -8px;
  background: #4CAF50;
  color: white;
  padding: 2px 8px;
  border-radius: 12px;
  font-size: 12px;
  font-weight: 600;
  box-shadow: 0 2px 8px rgba(76, 175, 80, 0.3);
}

.team-intro {
  color: #666;
  font-size: 14px;
  line-height: 1.6;
  margin-bottom: 16px;
  min-height: 40px;
}

.team-card-footer {
  display: flex;
  justify-content: flex-end;
}

.query-team-btn {
  padding: 8px 16px;
  background: linear-gradient(135deg, #667eea, #764ba2);
  color: white;
  border: none;
  border-radius: 6px;
  cursor: pointer;
  font-size: 13px;
  font-weight: 500;
  transition: all 0.3s ease;
  white-space: nowrap;
}

.query-team-btn:hover:not(:disabled) {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(102, 126, 234, 0.4);
}

.query-team-btn:disabled {
  opacity: 0.6;
  cursor: not-allowed;
}

.selected-team-info {
  margin-bottom: 16px;
}

.selected-team-info h3 {
  color: #667eea;
  font-size: 18px;
  font-weight: 600;
  padding: 12px 16px;
  background: rgba(102, 126, 234, 0.1);
  border-left: 4px solid #667eea;
  border-radius: 4px;
  margin: 0;
}

/* 旧的班级信息卡片样式（保留以防需要） */
.team-info-card {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border-radius: 12px;
  padding: 20px 24px;
  margin-bottom: 24px;
  color: white;
  box-shadow: 0 4px 12px rgba(102, 126, 234, 0.3);
}

.team-description {
  display: flex;
  align-items: baseline;
  gap: 8px;
  font-size: 14px;
  line-height: 1.6;
  opacity: 0.95;
}

.desc-label {
  font-weight: 500;
  white-space: nowrap;
}

.desc-text {
  flex: 1;
}

/* 作业列表区域 */
.homework-list-section {
  margin-top: 24px;
}

.list-title {
  margin: 0 0 16px 0;
  font-size: 18px;
  font-weight: 600;
  color: #333;
}

/* 空状态样式 */
.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 60px 20px;
  background: #fafafa;
  border-radius: 8px;
  margin-top: 24px;
}

.empty-icon {
  font-size: 64px;
  margin-bottom: 16px;
  opacity: 0.5;
}

.empty-text {
  margin: 0;
  font-size: 16px;
  color: #999;
  text-align: center;
}
</style> 